<template>
  <div class="users">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <!-- 搜索区域 -->
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserlist"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserlist"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户 -->
        <el-col :span="4">
          <el-button
            type="primary"
            class="addUsers"
            @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户信息表格 -->
      <el-table :data="userList" stripe border>
        <!-- 设置索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <!-- 此作用域插槽会覆盖上面的prop 所以prop删掉 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="rgb(36,102,47)"
              inactive-color="rgb(196,0,0)"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              class="btn_w green_btn"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              class="btn_w red_btn"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top">
              <el-button
                type="warning"
                icon="el-icon-star-off"
                class="btn_w"
                @click="setRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="40%"
        @close="addDialogClosed"
      >
        <!-- 添加用户的表单验证区域 -->
        <el-form
          :model="addForm"
          :rules="addRules"
          ref="addRulesForm"
          label-width="100px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser" class="red_btn"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!-- 修改用户信息对话框 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="editDialogVisible"
        width="40%"
        @close="editDialogClosed"
      >
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editEditInfo">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="setRolesdialogVisible"
        width="40%"
        @close="setRoleDialogClosed"
      >
        <div>
          <p>当前的用户：{{ userInfo.username }}</p>
          <p>当前的角色：{{ userInfo.role_name }}</p>
          <p>
            分配新角色：
            <el-select v-model="selectedRoleId" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRolesdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "users",
  data() {
    // todo 自定义邮箱的校验规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };
    // todo 自定义手机号的校验规则
    var checkMobile = (rule, value, callback) => {
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的手机号码"));
    };
    return {
      queryInfo: {
        // *搜索的关键字
        query: "",
        // *当前的页数
        pagenum: 1,
        // *当前每页显示的数据条数
        pagesize: 1,
      },
      userList: [],
      total: "" - 0,
      // pagenum: "",
      // *控制添加用户对话框是否显示
      addDialogVisible: false,
      //  *添加用户的信息
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // *添加用户的表单验证规则
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // *控制修改用户信息的对话框是否显示
      editDialogVisible: false,
      // * 修改用户信息表单内容
      editForm: {},
      //  *修改用户信息的校验规则
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // *控制分配角色对话框的显示与否
      setRolesdialogVisible: false,
      // *需要被分配角色的用户信息
      userInfo: {},
      // *所有角色列表
      rolesList: [],
      // *选中的角色id
      selectedRoleId: "",
    };
  },
  created() {
    this.getUserlist();
    // this.handleSizeChange(this.pagenum);
  },
  methods: {
    // a 获取用户列表数据的函数 在created时调用
    async getUserlist() {
      const res = await this.$http.get("users", { params: this.queryInfo });
      if (res.data.meta.status != 200) {
        return this.$message.error("获取用户列表失败！");
      }
      this.userList = res.data.data.users;
      this.total = res.data.data.total;
      this.pagenum = res.data.data.pagenum;
    },
    // *一个页面有几条 n条/页 修改时的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserlist();
    },
    // *当前在第几页的监听事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserlist();
    },
    // *修改用户状态按钮的回调函数
    async userStateChange(state) {
      // a 修改用户状态的请求
      const res = await this.$http.put(
        `users/${state.id}/state/${state.mg_state}`
      );
      if (res.data.meta.status != 200) {
        state.mg_state = !state.mg_state;
        return this.$message.error("用户状态更新失败！");
      }
      return this.$message.success("用户状态更新成功！");
      // });
    },
    //  * 监听添加用户对话框关闭时的事件
    addDialogClosed() {
      // *重置表单内容
      this.$refs.addRulesForm.resetFields();
    },
    //  *点击按钮添加用户
    addUser() {
      this.$refs.addRulesForm.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请检查填写是否正确！');
        } else {
          // a 校验值都成立 发起添加用户请求
          const res = await this.$http.post("users", this.addForm);
          if (res.data.meta.status != 201) {
            return this.$message.error("添加用户失败！");
          }
          this.addDialogVisible = false;
          this.getUserlist();
          return this.$message.success("添加用户成功！");
        }
      });
    },
    //  *点击修改按钮修改用户信息事件
    async showEditDialog(id) {
      this.editDialogVisible = true;
      // a 根据id查询用户信息
      const res = await this.$http.get("users/" + id);
      if (res.data.meta.status != 200) {
        return this.$message.error("查询用户信息失败");
      }
      this.editForm = res.data.data;
    },
    //  *关闭修改用户信息对话框时的事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //  *确定按钮 修改用户信息的事件
    editEditInfo() {
      // 提交修改前 校验值是否合理
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请检验用户信息是否合法！");
        }
        const res = await this.$http.put("users/" + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile,
        });
        if (res.data.meta.status !== 200) {
          return this.$message.error("用户信息修改失败！");
        }
        this.$message.success("用户信息修改成功！"); //* 提示更新成功
        this.getUserlist(); //*更新用户列表
      });
      this.editDialogVisible = false; // *关闭对话框
    },
    //  *单击删除按钮删除用户
    async removeUserById(id) {
      const removeUser = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((erro) => erro);
      if (removeUser !== "confirm") {
        return this.$message.info("已取消删除");
      }
      // a 发起删除用户请求
      const res = await this.$http.delete("users/" + id);
      if (res.data.meta.status !== 200) {
        this.$message.error("删除用户失败!");
      }
      this.$message.success("已成功删除该用户！"); //* 提示删除成功
      this.getUserlist(); //*更新用户列表
    },

    // *点击按钮显示分配角色对话框
    async setRoles(userInfo) {
      this.userInfo = userInfo;
      // a 获取角色列表
      const res = await this.$http.get("roles");
      if (res.data.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }
      this.rolesList = res.data.data;
      this.setRolesdialogVisible = true;
    },

    // *点击确定按钮分配角色
    async saveRoleInfo() {
      // *判断用户是否进行了选择
      if (!this.selectedRoleId) {
        return this.$message.error("请选择要分配的角色！");
      }
      // a 发送分配角色请求
      const res = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectedRoleId,
      });
      this.getUserlist();
      this.setRolesdialogVisible = false;
    },
    //*分配角色对话框的关闭事件
    setRoleDialogClosed() {
      //*重置下拉列表框
      this.selectedRoleId = "";
      this.userInfo = {};
    },
  },
};
</script>

<style scoped lang="less">
.addUsers {
  background-color: rgb(196, 0, 0);
  border: 1px solid rgb(196, 0, 0);
}
.btn_w {
  padding: 5px 10px;
}
.green_btn {
  background-color: rgb(36, 102, 47);
  border: 1px solid rgb(36, 102, 47);
}
.red_btn {
  background-color: rgb(196, 0, 0);
  border: 1px solid rgb(196, 0, 0);
}
</style>
